var express = require('express');
var router = express.Router();

var {Mvs} = require("../utils/model")
var {getDecrypt} = require("../utils");
var moment = require("moment")

/* GET home page. */
router.get('/', function(req, res, next) {
  console.log(req.session)
  moment.locale('zh-cn')
  res.render('home',{
    title:'电影评论管理系统',
    logintime:moment(req.session.logintime).format('llll'),
    username:req.session.username,
  });
});

router.get("/login",(req,res)=>{
  var username = req.query.username ? getDecrypt(req.query.username) : '' ;
  res.render("login",{username})
})

router.get("/register",(req,res)=>{
res.render("register");
})

//退出登录
router.get("/logout",(req,res) => {
  req.session.destroy(() => {
    res.redirect("/")
  })
})

// 修改密码
router.get("/changepass",(req,res)=>{
  if(req.session.username){
    res.render("changepass",{
      username:req.session.username
    })
  }else{
    res.send("<script>alert('Session已经过期无效,请重新登录');location.href='/login'</script>")
  }
})

//电影列表
router.get("/movie",(req,res)=>{
  if(req.session.username){
    var query = req.query;
    var keyword = query.keyword;
    var sortObj = {
      _id:1
    }
    console.log(query);
    var obj = {};
    if(keyword){
      obj={
        $or:[
          {title:new RegExp(keyword)},
          {year:new RegExp(keyword)},
          {genres:new RegExp(keyword)},
          {'rating.average':new RegExp(keyword)},
          {'directors.name':new RegExp(keyword)},
        ]
      }
    }else{
      sortObj = {...query,...sortObj} // 对象合并 ... 展开运算符 
    }   
    Mvs.find(obj,{
      _id:0
    }).sort(sortObj)
    .then(result=>{
        res.render("movie",{
          result,
          username:req.session.username
        })
    })
  }else{
    res.send("<script>alert('Session已经过期无效,请重新登录');location.href='/login'</script>")
  } 
})

router.post("/addone",(req,res)=>{
  res.json({
    msg:"添加成功",
    code:200,
    method:"POST",
    body:req.body  // post 请求提交的 data 数据
  })
})

module.exports = router;
